//
//  SignUpViewController.m
//  lvtu
//
//  Created by Apple on 12-3-9.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SignUpViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "DataSource.h"
#import "wxAppDelegate.h"

@implementation SignUpViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.title = @"注册";
    UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [tempLabel setText:@"注册"];
    [tempLabel setBackgroundColor:[UIColor clearColor]];
    [tempLabel setTextAlignment:UITextAlignmentCenter];
    [tempLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [tempLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = tempLabel;
    [tempLabel release];
    tempLabel = nil;
    
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.hidesBackButton = YES;
    isSexSelected = NO;
    
    backgroundScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    backgroundScrollView.backgroundColor = [UIColor clearColor];
    backgroundScrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height+100);
    
    backgroundScrollView.pagingEnabled = NO;
    backgroundScrollView.scrollEnabled = YES;
    backgroundScrollView.clipsToBounds = YES;
    backgroundScrollView.scrollsToTop = YES;
    backgroundScrollView.showsVerticalScrollIndicator = NO;
    backgroundScrollView.showsHorizontalScrollIndicator = NO;
    backgroundScrollView.delegate = self;
    [self.view addSubview:backgroundScrollView];
    
    UIImage* backImage = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton* leftbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftbutton.frame = CGRectMake(0, 0, backImage.size.width, backImage.size.height);
    [leftbutton setBackgroundImage:backImage forState:UIControlStateNormal];
    [leftbutton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [leftbutton addTarget:self action:@selector(returnButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* findoutButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftbutton];
    //signupButton.image = [UIImage imageNamed:@"btn_finish_normal.png"];
    self.navigationItem.leftBarButtonItem = findoutButtonItem;
    [findoutButtonItem release];
    
    UIImage* okImage = [UIImage imageNamed:@"btn_finish_normal.png"];
    UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightbutton.frame = CGRectMake(0, 0, okImage.size.width, okImage.size.height);
    [rightbutton setBackgroundImage:okImage forState:UIControlStateNormal];
    [rightbutton setBackgroundImage:[UIImage imageNamed:@"btn_finish_press.png"] forState:UIControlStateHighlighted];
    [rightbutton addTarget:self action:@selector(signup:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* signupButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightbutton];
    self.navigationItem.rightBarButtonItem = signupButtonItem;
    [signupButtonItem release];
    
    UILabel* mailLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 20, 50, 30)];
    mailLabel.text = @"邮箱 :";
    mailLabel.backgroundColor = [UIColor clearColor];
    mailLabel.font = [UIFont systemFontOfSize:13];
    [backgroundScrollView addSubview:mailLabel];
    [mailLabel release];
    
    mailTextField = [[UITextField alloc] init];
    UIImage* TextFieldImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_imput.png" ofType:nil]];
    [mailTextField setFrame:CGRectMake(40, 50, 240, 50)];
    [mailTextField setBackground:TextFieldImage];
    mailTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;                
    [mailTextField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [mailTextField setReturnKeyType:UIReturnKeyDefault];
    [mailTextField setFont:[UIFont boldSystemFontOfSize:12]];
    [mailTextField setDelegate:self];
    [mailTextField setTextColor:[UIColor grayColor]];
    [mailTextField setPlaceholder:@"作为登录账号，将来不可更改"];
    [mailTextField setKeyboardType:UIKeyboardTypeEmailAddress];
    [mailTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [mailTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [mailTextField setClipsToBounds:YES];
    [backgroundScrollView addSubview:mailTextField];
    [mailTextField release];
    
    UILabel* pswordLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 110, 50, 30)];
    pswordLabel.text = @"密码 :";
    pswordLabel.backgroundColor = [UIColor clearColor];
    pswordLabel.font = [UIFont systemFontOfSize:13];
    [backgroundScrollView addSubview:pswordLabel];
    [pswordLabel release];
    
    pswordTextField = [[UITextField alloc] init];
    [pswordTextField setFrame:CGRectMake(40, 140, 240, 50)];
    [pswordTextField setBackground:TextFieldImage];
    pswordTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;                
    [pswordTextField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [pswordTextField setReturnKeyType:UIReturnKeyDefault];
    [pswordTextField setFont:[UIFont boldSystemFontOfSize:12]];
    [pswordTextField setDelegate:self];
    [pswordTextField setTextColor:[UIColor grayColor]];
    [pswordTextField setPlaceholder:@"你的登录密码"];
    [pswordTextField setKeyboardType:UIKeyboardTypeDefault];
    [pswordTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [pswordTextField setClipsToBounds:YES];
    [backgroundScrollView addSubview:pswordTextField];
    [pswordTextField release];
    
    UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 200, 50, 30)];
    nameLabel.text = @"姓名 :";
    nameLabel.backgroundColor = [UIColor clearColor];
    nameLabel.font = [UIFont systemFontOfSize:13];
    [backgroundScrollView addSubview:nameLabel];
    [nameLabel release];
    
    nameTextField = [[UITextField alloc] init];
    [nameTextField setFrame:CGRectMake(40, 230, 240, 50)];
    [nameTextField setBackground:TextFieldImage];
    nameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;                
    [nameTextField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [nameTextField setReturnKeyType:UIReturnKeyDefault];
    [nameTextField setFont:[UIFont boldSystemFontOfSize:12]];
    [nameTextField setDelegate:self];
    [nameTextField setTextColor:[UIColor grayColor]];
    [nameTextField setPlaceholder:@"请填写真实姓名，方便朋友找到你"];
    [nameTextField setKeyboardType:UIKeyboardTypeDefault];
    [nameTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [nameTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [nameTextField setClipsToBounds:YES];
    [backgroundScrollView addSubview:nameTextField];
    [nameTextField release];
    
    UILabel* sexLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 300, 50, 30)];
    sexLabel.text = @"性别 :";
    sexLabel.backgroundColor = [UIColor clearColor];
    sexLabel.font = [UIFont systemFontOfSize:13];
    [backgroundScrollView addSubview:sexLabel];
    [sexLabel release];
    
    [self initSegment];
}

- (void) initSegment
{
    NSArray *itemArray = [NSArray arrayWithObjects: @"男", @"女",nil];  
    UISegmentedControl *_segmentOfPurposeOfAppointment = [[UISegmentedControl alloc] initWithItems: itemArray];  
    _segmentOfPurposeOfAppointment.frame = CGRectMake(90, 300, 160, 30);  
    _segmentOfPurposeOfAppointment.segmentedControlStyle = UISegmentedControlStylePlain;  
//    _segmentOfPurposeOfAppointment.selectedSegmentIndex = 1;  
    [_segmentOfPurposeOfAppointment addTarget:self  
                                       action:@selector(pickOne:)  
                             forControlEvents:UIControlEventValueChanged];  
    [backgroundScrollView addSubview:_segmentOfPurposeOfAppointment];
    [_segmentOfPurposeOfAppointment release];
}

- (void)pickOne: (id)sender  
{  
    UISegmentedControl *segmentControl = (id)sender;  
    NSInteger segment = segmentControl.selectedSegmentIndex;
    isSexSelected = YES;
    if (segment == 0)   
    {  
        sex = @"male";
    }  
    else if (segment == 1)  
    {
        sex = @"female";
    }
} 

- (void)viewDidUnload
{
    if (baseAlert) {
        [baseAlert release];
    }
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

- (void)signup:(id)sender
{
    if (isSexSelected == NO) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择性别" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2001;
        [alert show];
        [alert release];
        return;
    }
    NSString* psword = [[DataSource shareInstance] md5_hexDigest:pswordTextField.text];
    NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:mailTextField.text,@"email",psword,@"password",nameTextField.text,@"name",sex,@"sex",nil];
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = SIGNUP;
    msg.ui_delegate = self;
        
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=do_o_regist" postInfo:info userInfo:msg];
    baseAlert = [[UIAlertView alloc] initWithTitle:@"注册中..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [baseAlert show];
    
    UIActivityIndicatorView* aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    aiv.center = CGPointMake(baseAlert.bounds.size.width/2.0f, baseAlert.bounds.size.height-40.0f);
    [aiv startAnimating];
    [baseAlert addSubview:aiv];
    [aiv release];
}

- (void)returnButtonPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma -mark DataSourceDelegate

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    if ([coreMsg.data isEqual: SIGNUP]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"注册成功，正在登录" message:data delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        alert.tag = 2003;
        [alert show];
        [alert release];
        NSString* psword = [[DataSource shareInstance] md5_hexDigest:pswordTextField.text];
        NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:mailTextField.text/*@"martin.szj@gmail.com"*/,@"email",
                              psword/*@"123456"*/,@"password",
                              [[DataSource shareInstance] sys_getOSVersion],@"os",
                              LVTU_CLIENT_VERSION,@"version",
                              LVTU_CHANNEL,@"channel",
                              [[DataSource shareInstance] sys_getDeviceModelName],@"device_name",
                              [[DataSource shareInstance] sys_getDeviceID],@"device_id",
                              @"1",@"is_iphone",
                              nil];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = LOGININFO;
        msg.ui_delegate = self;
        
        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_o_login" postInfo:info userInfo:msg];
        
    }
    else  if([coreMsg.data isEqual: LOGININFO]){
        [[DataSource shareInstance] saveUserStatusToKeyChain:nameTextField.text passwd:pswordTextField.text];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = PERSONINFO;
        msg.ui_delegate = [wxAppDelegate getAppDelegate];
        
        [[NetDataSource shareInstance] postTo:@"http://www.wxlvtu.com/?a=page_personal_information" postInfo:nil userInfo:msg];
        
        //登录成功，进入主页面
        [[wxAppDelegate getAppDelegate] popAllViewController];
        [[wxAppDelegate getAppDelegate] showTabMainFrame];
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    if ([coreMsg.data isEqual: SIGNUP]) {
        NSString* msg;
        if ([data isEqualToString:@"email_existed"]) {
            msg = @"邮箱已经注册，请直接登录";
        }
        else {
            msg = (NSString*)data;
        }
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2001;
        [alert show];
        [alert release];
    }
}

- (void)alertViewCancel:(UIAlertView *)alertView
{
    if (alertView.tag == 2002) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didPresentAlertView:(UIAlertView *)alertView
{
    if (alertView.tag == 2003) {
        [alertView dismissWithClickedButtonIndex:0 animated:NO];
    }
}
#pragma -mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == mailTextField && [mailTextField.text isEqualToString:@"作为登录账号，将来不可更改"])
    {
        [mailTextField setText:@""];
        [mailTextField setTextColor:[UIColor blackColor]];
    }
    else if (textField == pswordTextField && [pswordTextField.text isEqualToString:@"你的登录密码"])
    {
        [pswordTextField setText:@""];
        [pswordTextField setTextColor:[UIColor blackColor]];
    }
    else if (textField == nameTextField && [nameTextField.text isEqualToString:@"请填写真实姓名，方便朋友找到你"])
    {
        [nameTextField setText:@""];
        [nameTextField setTextColor:[UIColor blackColor]];
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
//    if (textField == pswordTextField)
//    {
//        [backgroundScrollView setContentOffset:CGPointMake(0, 0) animated:YES]; 
//    }
//    else if (textField == nameTextField)
//    {
//        [backgroundScrollView setContentOffset:CGPointMake(0, 100) animated:YES]; 
//    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [mailTextField resignFirstResponder];
    [pswordTextField resignFirstResponder];
    [nameTextField resignFirstResponder];
//    [backgroundScrollView setContentOffset:CGPointMake(0, 0) animated:YES]; 
    if ( textField == mailTextField && [mailTextField.text isEqualToString:@""])
    {
        [mailTextField setPlaceholder:@"作为登录账号，将来不可更改"];
        [mailTextField setTextColor:[UIColor grayColor]];
    }
    else if ( textField == pswordTextField && [pswordTextField.text isEqualToString:@""])
    {
        [pswordTextField setPlaceholder:@"你的登录密码"];
        [pswordTextField setTextColor:[UIColor grayColor]];
    }
    else if ( textField == nameTextField && [nameTextField.text isEqualToString:@""])
    {
        [nameTextField setPlaceholder:@"请填写真实姓名，方便朋友找到你"];
        [nameTextField setTextColor:[UIColor grayColor]];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    
    if ([string isEqualToString:@"\n"])
    {//按下return键
        //这里隐藏键盘，不做任何处理
        [textField resignFirstResponder];
        //        [self willLoginWeibo];
        return NO;
    }
    else
    {
        return YES;
    }
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == mailTextField)
    {
        [mailTextField setText:@""];
        [mailTextField setPlaceholder:@"作为登录账号，将来不可更改"];
        [mailTextField setTextColor:[UIColor grayColor]];
    }
    else if (textField == pswordTextField)
    {
        [pswordTextField setText:@""];
        [pswordTextField setPlaceholder:@"你的登录密码"];
        [pswordTextField setTextColor:[UIColor grayColor]];
    }
    else if (textField == nameTextField)
    {
        [nameTextField setText:@""];
        [nameTextField setPlaceholder:@"请填写真实姓名，方便朋友找到你"];
        [nameTextField setTextColor:[UIColor grayColor]];
    }
    return YES;
}
@end
